﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Flurl.Http;
using Pay.Core;
using Pay.DTO;
using System.Web;

namespace Pay.Service {
	public class kySign {
		public kySign() {
		}

#if DEBUG
		protected string api_url = "http://test.qzhmpay.com/iPayInterface/odBusiness.do";
		/// <summary>
		/// 实名私钥
		/// </summary>
		protected string ky_privatekey = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDJJ9B0ibBhY5g/5+f7TkaUIfYlcZ/d69fiec6NobVFCA5e7h6MTM8lrY/KFQ0SoewYTSDwPkytmvbM5xNDioB8MeDSQUoMm/11zSv4QjZEDJQ9rR8ditooUzpIdBU5CAqDY9eQFu0xJhbviGFFmf/Wano0uhhJfxbEp8uu80ukkiOjUoO1Je3kwwk8B9+MEd4ezSlXaUFO2/09jwTvsqBbQRAwkP1OZJ4Ap84l8UMap5Nv7fqhPziV3A1Q9qYZMYY5qwDAQUr/zYFkbD2VIr7udQTWrmRY8VerT1UA+TO/olfCFl8Hbbg1P2Gwq1Lgtrvn7cI/wAMX8lp92neLZmlFAgMBAAECggEAWnWtKLtCtokzTonbqQfqdXNQXkZavlHxI8fjO44dFo4o6EftNOrVvPvwTdBpsJdgtQz6Yw+hK/EkS8EeyKDgZvmHQQZbZpA/y1oZC+u6u59sis/vzjlDIh9Ldom9gYg8MhoUNpgY0qFubwnFtKcshiAcFNobUfH1KzrKPkLrIXZKrsQt2NJU5GI5BWZqX+JDBj+lWaRAD3gyjUiEtm8CjpqrB51DVgvawS+4BGNdHsppAIZvGkSDkjksC/fOu5Qc3tA5eMbqvHSxIooF4Tcki6zXhzkCBhvKN6Sz6yakiUEZiLwftbGueFFaGVUGCHNWVYyeZP79zseZcvXDIepQAQKBgQDm5OFk5t/dm78bxCw6J/jy+uqxVug9ns0e2RDI6y3WG5k3TOZuYKLUoQ+wr8lmg39QAbJOa+p8B6iExKfGSiqBtTuWr6jfLNaOJ3GDpyBfJTbLQVz5A7E5o+8WSRlrA/qeg5pTudAHukyusKkCbaO9CKYVnGZ5vEOKHBllJVZQJQKBgQDfByNSQRGwMTAlRY1nEtLY/7oQYbTE+cjOOSyi3xnWOLsU6JjzqPge3xYW5NLLD3KwS6HTZPgx7zy4lx1xkZLlf9/G0ynDWg68jnafbQ/xsKG00ppxLYV3FbNBFQmen4hKQMxNBk62gi0wREFqmX1234hD+PvXESSY1l1e6N1aoQKBgB1JoRGEe5cHn3ktLBMAaQKhM03lYTYXw5sLG6bwtfK3s3qhRYVwupbQC0Z1Nc3MFkUWwgBSjf7HleepbkKnu7aSP4nApGIStPB5LlvtwhxvgwDLPLjVcBCIq9Ye1ZuOeKbMuLGwGyQvzHRIMlf9gkyDIVYSbak5aTPGlq4Oy2EFAoGAaUOhNC1p/9L3el/9gWys/6aTVzAGdgG++TabDrRmKWnVQuUVa8uQcGGyt1OA+j5sTzEjS/cX/dmAu073oqamwpM8N0drKrzSv8Qt0MlVASnw6LuOEWT+3VnspQcc5zU8ym8S/je/5vxB/8n3ZizTvst6MTrPAo8gytJCd41JDIECgYEAm+78JogzEcqpEAFUdcqDtqADdVExO+RzUo+993VnqtSy5apJAJQ3BAwDTESswUcoElXnpWhjnDdiY5IoQKND+RPVpwWZBFBEKAp0497PeVGzZWXx15+31tMG9he6eK+22Ami8Sj2wen4TTCkQCSett20/TVCQNgOXGX04bD9/VM=";
		/// <summary>
		/// 实名公钥
		/// </summary>
		protected string _ky_publickey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAySfQdImwYWOYP+fn+05GlCH2JXGf3evX4nnOjaG1RQgOXu4ejEzPJa2PyhUNEqHsGE0g8D5MrZr2zOcTQ4qAfDHg0kFKDJv9dc0r+EI2RAyUPa0fHYraKFM6SHQVOQgKg2PXkBbtMSYW74hhRZn/1mp6NLoYSX8WxKfLrvNLpJIjo1KDtSXt5MMJPAffjBHeHs0pV2lBTtv9PY8E77KgW0EQMJD9TmSeAKfOJfFDGqeTb+36oT84ldwNUPamGTGGOasAwEFK/82BZGw9lSK+7nUE1q5kWPFXq09VAPkzv6JXwhZfB224NT9hsKtS4La75+3CP8ADF/Jafdp3i2ZpRQIDAQAB";
		/// <summary>
		/// 快捷私钥
		/// </summary>
		protected string kj_privatekey = "<RSAKeyValue><Modulus>svQt97qsOswSi+pShEMIVfj5BCgOfvso92IKhh5L9Q8Xsa0lQygVlyEJXk+JPyMyHvgTks0L9Z2qBt3iPwVe0Q==</Modulus><Exponent>AQAB</Exponent><P>4fdUP4nz6LSO5C/7gMPdXLxo4W8tesPiYbAg0CquQoU=</P><Q>yr04hgNrqAR+bIgzHi5wL92leoz2P+MYCwR9DyuFyt0=</Q><DP>y53iJcs6pZOmOwrdt79HBlykqZdURQ6kPODIAKylED0=</DP><DQ>H99VhoP9JcHnGirjVmhYjL3cqQKGKA8MlZbUDlF6TCU=</DQ><InverseQ>Il1RYs6bO+EhHoKTn1nEd08peECNtA8BxZDfMBnjxG8=</InverseQ><D>BQhO3p+WRlUE1IBzb5q++kP1JMPHnJSNk19jcmAZvLty3clyR5dq/R/K2okkbaK4c+NqsUbzrWVzzQNV0ZxJUQ==</D></RSAKeyValue>";
		/// <summary>
		/// 快捷公钥
		/// </summary>
		protected string kj_publickey = "<RSAKeyValue><Modulus>0GQeXfI5s3XgwvPWN/SD3TLHxeJGTBBzOfaCzy2IN6VYMXgOvFsmpCD0jH6nvbRcvZyGkBQYylfoZNW8MkEmCw==</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>";
		protected string appid = "f8e7839f-7578-420c-a170-e28be0cf44d7";
		protected string appcode = "17e3cac1-bd9c-4d99-bf50-96e03db004de";
#else
		protected string api_url = "";
		/// <summary>
		/// 实名私钥
		/// </summary>
		protected string ky_privatekey = "";
		/// <summary>
		/// 实名公钥
		/// </summary>
		protected string _ky_publickey = "";
		/// <summary>
		/// 快捷私钥
		/// </summary>
		protected string kj_privatekey = "<RSAKeyValue><Modulus>0HhGT9pTlTIb4DkTSt3/tQ5OQax3CdNqMX7PXAS7aYmz+Cpo6bxFTZ+Tp6W1+xFxW8fwMxaCzf7Tvo8AgvY1tw==</Modulus><Exponent>AQAB</Exponent><P>/rpKVFIZXOV+Cy3YDGXJIFpezQyM5kdoolflWtQw988=</P><Q>0YLWF6hyVfXuSr7E1T3SH1owkCNW49NGczTcUKwn9Zk=</Q><DP>w0aK7uNVYDrqiqVlZ/Or4SqGXIlPhsWdeD8Lq7rZo08=</DP><DQ>S1l0yhlo1YWXaAZoIBEVyvTS1mP/UfygL7rpKZJg5LE=</DQ><InverseQ>c8R9V0V3k1X0nMSk7xyJQk+gdZ+zOecCYugcjuLRDQU=</InverseQ><D>GHBxNb1PnScBs5idVWKPLqedrv9L+T/qrCDEqHH5kpaWsP+rwlK8aFzveLTBR/uYOJVeTrqsgoDvuCDtPWA48Q==</D></RSAKeyValue>";
		/// <summary>
		/// 快捷公钥
		/// </summary>
		protected string kj_publickey = "<RSAKeyValue><Modulus>0GQeXfI5s3XgwvPWN/SD3TLHxeJGTBBzOfaCzy2IN6VYMXgOvFsmpCD0jH6nvbRcvZyGkBQYylfoZNW8MkEmCw==</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>";
		protected string appid = "ccb7572e-08f2-4033-b63f-64ce3ed2d84e";
		protected string appcode = "a30d38c3-79ea-4332-aff7-e86d03f48997";
#endif
		/// <summary>
		/// 卡友实名方法
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="model"></param>
		/// <returns></returns>
		public async Task<T> PayGateway<T>(ky_head_base model) where T : ky_base_result, new() {
			var log = IocHelper.Get<ILogHelper>("info");
			try {
				model.SIGN = Sign(model);
				var data = model.ToJson();
				log.Info(data);
				var resp = await api_url.PostUrlEncodedAsync(new { REQ_DATA = HttpUtility.UrlEncode(data, Encoding.UTF8) }).ReceiveString();
				var result = HttpUtility.UrlDecode(resp, Encoding.UTF8).ToObject<T>();
				log.Info(result.ToJson());
				return result;
			} catch (FlurlHttpException ex) {
				log.Error(ex.Message);
				return null;
			}
		}

		/// <summary>
		/// 快捷支付请求
		/// </summary>
		/// <returns>The gateway.</returns>
		/// <param name="model">Model.</param>
		public string PayGateway(ky_head_query model) {
			var log = IocHelper.Get<ILogHelper>("info");
			try {
				var data = model.ToJson("sign");
				log.Info(data);
				data = WebHelper.UrlEncode(RSAFromPkcs.RSAEncrypt(data, kj_publickey));
				//log.Info("http://unpay.78mi.cn/sys/api/Payurl?data=" + data);
				//var resp = "http://unpay.78mi.cn/sys/api/Payurl?data=" + data;
				log.Info("http://unpay.qzhmpay.com/sys/api/payurl?data=" + data);
				var resp = "http://unpay.qzhmpay.com/sys/api/payurl?data=" + data;
				return resp;
			} catch (Exception ex) {
				log.Error(ex.Message);
				return null;
			}
		}

		/// <summary>
		/// 实名sign签名
		/// </summary>
		/// <param name="model"></param>
		/// <param name="filter"></param>
		/// <returns></returns>
		public string Sign(ky_head_base model, params string[] filter) {
			string json = model.ToJson();
			var collection = json.ToObject<SortedDictionary<string, object>>();
			collection.Remove("sign");
			if (filter != null) {
				foreach (var f in filter)
					collection.Remove(f);
			}
			string result = string.Empty;
			foreach (var kv in collection) {
				if (kv.Value != null && !string.IsNullOrEmpty(kv.Value.ToString()))
					result += "&" + kv.Key + "=" + kv.Value;
			}
			result = result.Trim('&');
			var log = IocHelper.Get<ILogHelper>("info");
			log.Error(result);
			result = RSAFromPkcs.sign(result, ky_privatekey, "utf-8");
			return result;
		}

		/// <summary>
		/// sign验签
		/// </summary>
		/// <param name="model"></param>
		/// <returns></returns>
		public bool VerifySign(string data, out ky_quick_result ky_result) {
			var log = IocHelper.Get<ILogHelper>("info");
			var datajson = RSAFromPkcs.RSADecrypt(data, kj_privatekey);
			log.Error(datajson);
			ky_result = datajson.ToObject<ky_quick_result>();
			var collection = datajson.ToObject<SortedDictionary<string, object>>();
			var sign = collection["sign"].ToString();
			collection.Remove("sign");
			collection.Remove("paychannelcode");
			collection.Add("appid", appid);
			collection.Add("appcode", appcode);
			string result = string.Empty;
			foreach (var kv in collection) {
				if (kv.Value != null && !string.IsNullOrEmpty(kv.Value.ToString()))
					result += "&" + kv.Key + "=" + kv.Value;
			}
			result = result.Trim('&');
			log.Error(result);
			result = SecureHelper.MD5(result).ToUpper();
			return result == sign;
		}

		public async Task<ky_quick_query> PayGateway2(ky_head_query model) {
			var log = IocHelper.Get<ILogHelper>("info");
			try {
				var collection = model.ToJson().ToObject<SortedDictionary<string, object>>();
				collection.Remove("sign");
				//url query
				var query = "";
				foreach (var kv in collection) {
					if (kv.Value != null && !string.IsNullOrEmpty(kv.Value.ToString()))
						query += "&" + kv.Key + "=" + kv.Value;
				}
				query = query.Trim('&');
				//sign 
				collection.Add("appid", appid);
				collection.Add("appcode", appcode);
				string result = string.Empty;
				foreach (var kv in collection) {
					if (kv.Value != null && !string.IsNullOrEmpty(kv.Value.ToString()))
						result += "&" + kv.Key + "=" + kv.Value;
				}
				result = result.Trim('&');
				model.sign = SecureHelper.MD5(result).ToUpper();
				query += "&sign=" + model.sign;
				//end
				var data = model.ToJson();
				log.Info(data);
				var resp = await ("http://unpay.78mi.cn/sys/api/GetOrderInfo?" + query).PostJsonAsync(null).ReceiveJson<ky_quick_query>();
				log.Info(resp.ToJson());
				return resp;
			} catch (FlurlHttpException ex) {
				log.Error(ex.Message);
				return null;
			}
		}
	}
}
